package com.dhl.fin.api.service;

import com.dhl.fin.api.common.domain.BasicDomain;
import com.dhl.fin.api.common.dto.QueryDto;
import com.dhl.fin.api.common.service.CommonService;
import com.dhl.fin.api.common.util.ObjectUtil;
import com.dhl.fin.api.common.util.WebUtil;
import com.dhl.fin.api.domain.DataPer;
import com.dhl.fin.api.domain.Tree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by CuiJianbo on 2020.02.23.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DataPerServiceImpl extends CommonService<DataPer> {

    @Autowired
    private TreeServiceImpl treeService;

    /**
     * 用于saveDomain方法前对domain的校验, 主要是服务前端
     * <p>
     * 返回数据为前端显示的提示信息
     *
     * @param domain
     * @return 为null为校验通过，非null的为校验不通过
     * @throws Exception
     */
    @Override
    public String validate(DataPer domain) throws Exception {
        Long nodeId = WebUtil.getLongParam("nodeId");
        nodeId = ObjectUtil.isNull(nodeId) ? -1 : nodeId;
        BasicDomain dataPer = checkUnique(DataPer.class, "code", domain.getCode(), "data_per.tree_id != " + nodeId);
        if (ObjectUtil.notNull(dataPer)) {
            return String.format("code为%s的数据已存在", domain.getCode());
        }
        return null;
    }

    /**
     * 在保存前
     *
     * @param domain
     */
    @Override
    public void beforeSave(DataPer domain) throws Exception {
        Long parentId = WebUtil.getLongParam("parentNodeId");
        Long nodeId = WebUtil.getLongParam("nodeId");
        if (ObjectUtil.isNull(nodeId)) {
            Tree parentTree = null;
            if (ObjectUtil.isNull(parentId)) {
                Tree rootTreeDb = checkUnique(Tree.class, "code", "area_data_root");
                if (ObjectUtil.notNull(rootTreeDb)) {
                    parentTree = rootTreeDb;
                    parentTree.setRemove(false);
                } else {
                    parentTree = new Tree(null, "区域数据根节点", "area_data_root", null);
                }
            } else {
                parentTree = new Tree(parentId, null, null, null);
            }
            Tree tree = new Tree(null, domain.getName(), domain.getCode(), null);
            tree.setParent(parentTree);
            treeService.saveDomain(tree);
            domain.setTree(tree);
        } else {
            QueryDto queryDto = QueryDto.builder().available().addWhere("tree.id=" + nodeId).build();
            domain.setId(get(queryDto).getId());

            Tree node = treeService.get(nodeId);
            node.setTitle(domain.getName());
            treeService.saveDomain(node);

        }

    }
}



